package com.mxs.qrcode.utils.alisms;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.QuerySendDetailsRequest;
import com.aliyun.dysmsapi20170525.models.QuerySendDetailsResponse;
import com.aliyun.dysmsapi20170525.models.QuerySendDetailsResponseBody;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import java.text.SimpleDateFormat;
import java.util.Date;

public class AliSmsQueryDetails {


    private static String OK_CODE = "OK";

    /**
     *
     * @param client
     * @param phoneNumber 必填  接收短信的手机号码。
     * @param sendDate 必填 短信发送日期，支持查询最近30天的记录。
     * @param pageNo  指定发送记录的当前页码
     * @param pageSize 指定每页显示的短信记录数量 取值范围为1~50。
     * @param bizId  发送回执ID，即发送流水号。调用发送接口SendSms或SendBatchSms发送短信时，返回值中的BizId字段。
     * @return
     *{
     *   "TotalCount": 1,
     *   "Message": "OK",
     *   "RequestId": "819BE656-D2E0-4858-8B21-B2E477085AAF",
     *   "Code": "OK",
     *   "SmsSendDetailDTOs": {
     *     "SmsSendDetailDTO": {
     *       "TemplateCode": "SMS_122310183",
     *       "ReceiveDate": "2019-01-08 16:44:13",
     *       "PhoneNum": 15200000000,
     *       "Content": "【阿里云】验证码为：123，您正在登录，若非本人操作，请勿泄露",
     *       "SendStatus": 3,
     *       "OutId": 123,
     *       "SendDate": "2019-01-08 16:44:10",
     *       "ErrCode": "DELIVERED"
     *     }
     *   }
     * }
     *
     * @throws Exception
     */
    public static JsonObject querySendDetails(Client client,String phoneNumber, Date sendDate,
                                 Long pageNo, Long pageSize, String bizId) throws Exception {
        if(sendDate == null){
            throw new Exception("");
        }
        if(pageNo ==null){
            pageNo =1L;
        }
        if(pageSize == null){
            pageSize = 10L;
        }
        if(pageSize>50){
            pageSize = 50L;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        QuerySendDetailsRequest querySendDetailsRequest = new QuerySendDetailsRequest()
                .setPhoneNumber(phoneNumber)
                .setSendDate(sdf.format(sendDate))
                .setPageSize(pageNo)
                .setCurrentPage(pageSize)
                .setBizId(bizId);
        QuerySendDetailsResponse detailsResponse =client.querySendDetails(querySendDetailsRequest);
        QuerySendDetailsResponseBody body =detailsResponse.getBody();
        Gson gson = new Gson();
        String jsonStr = gson.toJson(body);
        if(OK_CODE.equals(body.getCode())){
            return gson.fromJson(jsonStr, JsonObject.class);
        }else{
            throw new Exception(jsonStr);
        }

    }
}
